/*
 * @lc app=leetcode.cn id=859 lang=javascript
 *
 * [859] 亲密字符串
 */

// @lc code=start
/**
 * @param {string} s
 * @param {string} goal
 * @return {boolean}
 */
var buddyStrings = function (s, goal) {
  if (s.length !== goal.length) return false;
  let index = [];
  let sum = 0;
  let map = new Array(26).fill(0);
  let sign = false;
  for (let i = 0; i < s.length; i++) {
    if (++map[s.charCodeAt(i) - 'a'.charCodeAt()] > 1) sign = true;
    if (s.charAt(i) !== goal.charAt(i)) {
      if (sum === 2) return false;
      index[sum++] = i;
    }
  }
  if (sum === 0) return sign;
  if (sum === 1) return false;
  return s.charAt(index[0]) === goal.charAt(index[1]) &&
    s.charAt(index[1]) === goal.charAt(index[0])
};
// @lc code=end
